// 引入ECharts
const echarts = require('../../utils/echarts-mini');

// 导入全局认证管理器
import { authManager } from '../../api/auth-manager';
const i18n = require('../../i18n/index');

// 统一日志标识
const LOG_PREFIX = '📊 [stats]';

// 周几的常量数组
const WEEKDAYS = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

// 本地化辅助：月份、天、周几与饮品类型
function localizeMonthLabel(m: number): string {
  const lang = i18n.getLang();
  if (lang === 'en-US') return `${m}`; // 纯数字，轴上更简洁
  return `${m}月`;
}
function localizeDayLabel(d: number): string {
  const lang = i18n.getLang();
  if (lang === 'en-US') return `${d}`;
  return `${d}日`;
}
function localizeHourLabel(h: string): string { return h; }
function localizeWeekdayLabel(i: number): string {
  const lang = i18n.getLang();
  const zh = ['周一','周二','周三','周四','周五','周六','周日'];
  const en = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
  const hk = ['週一','週二','週三','週四','週五','週六','週日'];
  if (lang === 'en-US') return en[i];
  if (lang === 'zh-HK') return hk[i];
  return zh[i];
}
function localizeTypeName(name: string): string {
  // 统一使用 water 模块类型键名映射
  const mapCN: any = { '白开水': 'water', '白水': 'water', '茶水': 'tea', '果汁': 'juice', '咖啡': 'coffee', '其他': 'other' };
  const key = mapCN[name] || name;
  const t = (k: string) => i18n.t(`water.${k}`);
  const table: any = {
    water: t('typeWater'), tea: t('typeTea'), coffee: t('typeCoffee'), juice: t('typeJuice'), milk: t('typeMilk'), sports: t('typeSports'), other: t('typeOther')
  };
  return table[key] || name;
}

// 将演示数据的标签名根据语言重新映射
function localizeDemoTrend(period: string, data: any[]): any[] {
  if (!Array.isArray(data)) return data;
  if (period === 'year') {
    return data.map((it: any, idx: number) => ({ ...it, name: localizeMonthLabel(idx + 1) }));
  }
  if (period === 'month') {
    return data.map((it: any) => {
      const d = parseInt(String(it.name).replace(/[^0-9]/g, '')) || 1;
      return { ...it, name: localizeDayLabel(d) };
    });
  }
  if (period === 'week') {
    const map = [0,1,2,3,4,5,6].map((i) => localizeWeekdayLabel(i));
    // 源数据顺序为 周一..周日
    return data.map((it: any, i: number) => ({ ...it, name: map[i] }));
  }
  if (period === 'day') {
    return data.map((it: any) => ({ ...it, name: localizeHourLabel(it.name) }));
  }
  return data;
}
function localizeDemoTypes(types: any[]): any[] {
  if (!Array.isArray(types)) return types;
  return types.map((it: any) => ({ ...it, name: localizeTypeName(it.name) }));
}

// 默认演示数据（保留数值，标签将按语言在运行时本地化）
const DEMO_DATA = {
  year: {
    total: 5472,
    avg: 15,
    days: 291,
    totalDays: 365,
    trend: Array.from({ length: 12 }, (_, i) => ({ name: `${i + 1}月`, value: [420,390,450,480,460,440,500,480,450,470,430,400][i] })),
    types: [
      { name: '白开水', value: 3283, color: '#0ea5e9' },
      { name: '茶水', value: 1094, color: '#38bdf8' },
      { name: '果汁', value: 657, color: '#7dd3fc' },
      { name: '咖啡', value: 274, color: '#0284c7' },
      { name: '其他', value: 164, color: '#0369a1' }
    ]
  },
  month: {
    total: 450,
    avg: 15,
    days: 25,
    totalDays: 30,
    trend: [1,5,10,15,20,25,30].map((d, idx) => ({ name: `${d}日`, value: [18,15,16,14,17,13,15][idx] })),
    types: [
      { name: '白开水', value: 270, color: '#0ea5e9' },
      { name: '茶水', value: 90, color: '#38bdf8' },
      { name: '果汁', value: 45, color: '#7dd3fc' },
      { name: '咖啡', value: 27, color: '#0284c7' },
      { name: '其他', value: 18, color: '#0369a1' }
    ]
  },
  week: {
    total: 105,
    avg: 15,
    days: 6,
    totalDays: 7,
    trend: ['周一','周二','周三','周四','周五','周六','周日'].map((n, idx) => ({ name: n, value: [18,15,16,14,17,13,12][idx] })),
    types: [
      { name: '白开水', value: 63, color: '#0ea5e9' },
      { name: '茶水', value: 21, color: '#38bdf8' },
      { name: '果汁', value: 10.5, color: '#7dd3fc' },
      { name: '咖啡', value: 6.3, color: '#0284c7' },
      { name: '其他', value: 4.2, color: '#0369a1' }
    ]
  },
  day: {
    total: 15,
    avg: 15,
    days: 1,
    totalDays: 1,
    trend: ['6:00','9:00','12:00','15:00','18:00','21:00'].map((t, idx) => ({ name: t, value: [2,3,2.5,2,3,2.5][idx] })),
    types: [
      { name: '白开水', value: 9, color: '#0ea5e9' },
      { name: '茶水', value: 3, color: '#38bdf8' },
      { name: '果汁', value: 1.5, color: '#7dd3fc' },
      { name: '咖啡', value: 0.9, color: '#0284c7' },
      { name: '其他', value: 0.6, color: '#0369a1' }
    ]
  }
};

// 定义数据接口
interface TrendDataItem { name: string; value: number; }
interface TypeDataItem { name: string; value: number; color: string; }

Page({
  data: {
    // Header 数据
    pageTitle: '数据分析中心',
    pageTip: '科学饮水，健康生活～',
    
    // 多语言
    l10n: {
      headerTitle: '', headerTip: '', loginMessage: '', loginDesc: '', loginBtn: '',
      demoTitle: '', demoDesc: '', demoLabel: '', demoTag: '',
      periodToday: '', periodWeek: '', periodMonth: '', periodYear: '',
      sumTotal: '', sumAvg: '', sumDays: '', sumRate: '',
      trendTitle: '', typeTitle: '', loading: '', noData: '',
      trendSubtitleSuffix: '', typeSubtitle: '',
      introTitle: '', introItem1: '', introItem2: '', introItem3: '', introItem4: '', tryBtn: ''
    },
    
    // Login 状态
    isLoggedIn: false,
    selectedPeriod: 'year', // 默认为全年
    periodTitle: '全年',
    
    // 统计数据
    totalAmount: '0ml',
    avgAmount: '0ml',
    completionDays: 0,
    totalDays: 365,
    completionRate: 0,
    
    // 数据状态标识
    isDemo: true,
    
    // 图表显示控制
    showTrendChart: false,
    showTypeChart: false,
    forceUseOldCanvas: true,
    
    // 加载状态
    isLoading: false,
    
    // 图表数据
    trendChartData: [] as TrendDataItem[],
    typeChartData: [] as TypeDataItem[],
    
    // 默认颜色配置
    defaultColors: ['#0ea5e9', '#38bdf8', '#7dd3fc', '#0284c7', '#0369a1'],
    
    // ECharts配置
    trendChart: { onInit: null as any },
    typeChart: { onInit: null as any }
  },

  // ECharts实例
  trendChartInstance: null as any,
  typeChartInstance: null as any,
  langUnsub: null as (() => void) | null,

  onLoad() {
    console.log(LOG_PREFIX + ' 统计页面加载开始');
    
    // 多语言初始化
    this.updateTexts();
    this.langUnsub = i18n.onLangChange(() => {
      this.updateTexts();
      // 语言切换后，重本地化并刷新当前周期数据和图表
      this.updateStatsForPeriod(this.data.selectedPeriod);
    });
    
    // 检查登录状态
    this.checkLoginStatus();
    
    // 检测运行环境
    this.detectEnvironment();
    
    // 立即设置图表初始化函数
    this.initCharts();
    
    // 加载演示数据
    this.loadDemoData();
  },

  /**
   * 页面显示时的处理
   */
  onShow() {
    console.log(LOG_PREFIX, 'onShow');
    // 刷新多语言标题
    this.updateTexts();
    // 刷新登录状态和数据
    this.checkLoginStatus();
  },

  onUnload() {
    if (this.langUnsub) { try { this.langUnsub(); } catch (_) {} this.langUnsub = null; }
  },

  updateTexts() {
    const t = (k: string) => i18n.t(`stats.${k}`);
    const l10n = {
      headerTitle: t('headerTitle'), headerTip: t('headerTip'), loginMessage: t('loginMessage'), loginDesc: t('loginDesc'), loginBtn: t('loginBtn'),
      demoTitle: t('demoTitle'), demoDesc: t('demoDesc'), demoLabel: t('demoLabel'), demoTag: t('demoTag'),
      periodToday: t('periodToday'), periodWeek: t('periodWeek'), periodMonth: t('periodMonth'), periodYear: t('periodYear'),
      sumTotal: t('sumTotal'), sumAvg: t('sumAvg'), sumDays: t('sumDays'), sumRate: t('sumRate'),
      trendTitle: t('trendTitle'), typeTitle: t('typeTitle'), loading: t('loading'), noData: t('noData'),
      trendSubtitleSuffix: t('trendSubtitleSuffix'), typeSubtitle: t('typeSubtitle'),
      introTitle: t('introTitle'), introItem1: t('introItem1'), introItem2: t('introItem2'), introItem3: t('introItem3'), introItem4: t('introItem4'), tryBtn: t('tryBtn')
    };
    this.setData({ l10n });
    try { wx.setNavigationBarTitle({ title: t('title') }); } catch (e) {}
  },

  // 检查登录状态
  checkLoginStatus() {
    try {
      const isLoggedIn = authManager.isAuthenticated();
      const currentUser = authManager.getCurrentUser();
      const userName = currentUser?.nickname || currentUser?.username || '';
      
      const headerTitle = isLoggedIn ? i18n.t('home.greeting').replace('{name}', userName || i18n.t('home.guest')) : i18n.t('stats.headerTitle');
      this.setData({ 
        isLoggedIn,
        pageTitle: headerTitle
      });
      console.log(LOG_PREFIX + ' 登录状态:', isLoggedIn, '用户名:', userName);
    } catch (e) {
      console.error(LOG_PREFIX + ' 检查登录状态失败:', e);
    }
  },

  // 检测运行环境
  detectEnvironment() {
    const systemInfo = wx.getSystemInfoSync();
    console.log(LOG_PREFIX + ' 检测到系统信息:', systemInfo.platform);
    
    // PC端强制使用旧版Canvas
    if (systemInfo.platform === 'windows' || systemInfo.platform === 'mac') {
      this.setData({ forceUseOldCanvas: true });
    }
  },

  // 初始化图表
  initCharts() {
    console.log(LOG_PREFIX + ' 开始初始化图表');
    this.setData({ 'trendChart.onInit': this.initTrendChart.bind(this), 'typeChart.onInit': this.initTypeChart.bind(this) });
    console.log(LOG_PREFIX + ' 图表初始化函数设置完成');
  },

  // 初始化趋势图表
  initTrendChart(canvas: any, width: number, height: number, dpr: number) {
    try {
      console.log(LOG_PREFIX + ' 初始化趋势图表, 尺寸:', width, 'x', height);
      const chart = echarts.init(canvas, null, { width, height, devicePixelRatio: dpr });
      this.trendChartInstance = chart;
      setTimeout(() => { this.updateTrendChart(); }, 100);
      return chart;
    } catch (error) {
      console.error(LOG_PREFIX + ' 初始化趋势图表失败:', error);
      return null;
    }
  },

  // 初始化类型图表
  initTypeChart(canvas: any, width: number, height: number, dpr: number) {
    try {
      console.log(LOG_PREFIX + ' 初始化类型图表, 尺寸:', width, 'x', height);
      const chart = echarts.init(canvas, null, { width, height, devicePixelRatio: dpr });
      this.typeChartInstance = chart;
      setTimeout(() => { this.updateTypeChart(); }, 100);
      return chart;
    } catch (error) {
      console.error(LOG_PREFIX + ' 初始化类型图表失败:', error);
      return null;
    }
  },

  // 加载演示数据
  loadDemoData() {
    this.setData({ isLoading: true });
    setTimeout(() => {
      this.updateStatsForPeriod(this.data.selectedPeriod);
      this.setData({ isLoading: false });
    }, 500);
  },

  // 选择时间周期
  selectPeriod(e: any) {
    const period = e.currentTarget.dataset.period;
    console.log(LOG_PREFIX + ' 选择时间周期:', period);
    this.setData({ selectedPeriod: period, isLoading: true });
    setTimeout(() => {
      this.updateStatsForPeriod(period);
      this.setData({ isLoading: false });
    }, 300);
  },

  // 更新指定周期的统计数据
  updateStatsForPeriod(period: string) {
    const base = DEMO_DATA[period as keyof typeof DEMO_DATA];
    if (!base) { console.error(LOG_PREFIX + ' 找不到周期数据:', period); return; }
    console.log(LOG_PREFIX + ' 更新周期数据:', period, base);

    // 本地化标签
    const trendLocalized = localizeDemoTrend(period, base.trend);
    const typesLocalized = localizeDemoTypes(base.types);

    // 更新基础统计
    const completionRate = Math.round((base.days / base.totalDays) * 100);

    this.setData({
      periodTitle: this.getPeriodTitle(period),
      totalAmount: this.formatAmount(base.total),
      avgAmount: this.formatAmount(base.avg),
      completionDays: base.days,
      totalDays: base.totalDays,
      completionRate: completionRate,
      trendChartData: trendLocalized,
      typeChartData: typesLocalized,
      showTrendChart: true,
      showTypeChart: true
    });

    setTimeout(() => {
      this.updateTrendChart();
      this.updateTypeChart();
    }, 200);
  },

  // 获取周期标题
  getPeriodTitle(period: string): string {
    const t = (k: string) => i18n.t(`stats.${k}`);
    const titles: Record<string, string> = { day: t('periodToday'), week: t('periodWeek'), month: t('periodMonth'), year: t('periodYear') };
    return titles[period] || t('periodYear');
  },

  // 格式化数量 (现在数据以升为单位存储)
  formatAmount(amount: number): string {
    if (amount >= 1) return amount.toFixed(1) + 'L';
    return (amount * 1000).toFixed(0) + 'ml';
  },

  // 更新趋势图表
  updateTrendChart() {
    console.log(LOG_PREFIX + ' 更新趋势图表, 实例:', !!this.trendChartInstance, '数据:', this.data.trendChartData?.length, '具体数据:', this.data.trendChartData);
    if (!this.trendChartInstance) { setTimeout(() => this.updateTrendChart(), 3000); return; }
    if (!this.data.trendChartData || this.data.trendChartData.length === 0) return;
    const option = {
      backgroundColor: 'transparent',
      color: ['#0ea5e9'],
      tooltip: {
        trigger: 'axis',
        formatter: (params: any) => {
          if (!params || !params[0]) return '';
          const value = params[0].value;
          const formatted = value >= 1 ? value.toFixed(1) + 'L' : (value * 1000).toFixed(0) + 'ml';
          return `${params[0].name}: ${formatted}`;
        }
      },
      grid: { left: '8%', right: '8%', top: '10%', bottom: '25%', containLabel: false },
      xAxis: {
        type: 'category',
        data: this.data.trendChartData.map((item: any) => item.name),
        axisLine: { lineStyle: { color: '#e5e7eb' } },
        axisTick: { show: false },
        axisLabel: {
          color: '#6b7280', fontSize: 8,
          interval: this.data.selectedPeriod === 'day' ? 'auto' : 0,
          rotate: this.data.selectedPeriod === 'year' ? 45 : 0,
          margin: 8
        }
      },
      yAxis: { type: 'value', show: false },
      series: [{
        data: this.data.trendChartData.map((item: any) => item.value),
        type: 'bar', barWidth: this.data.selectedPeriod === 'day' ? '40%' : '50%',
        itemStyle: { color: '#0ea5e9', borderRadius: [2, 2, 0, 0] },
        label: { show: false }
      }]
    } as any;
    try { this.trendChartInstance.setOption(option); } catch (error) { console.error(LOG_PREFIX + ' 趋势图表设置失败:', error); }
  },

  // 更新类型图表
  updateTypeChart() {
    console.log(LOG_PREFIX + ' 更新类型图表, 实例:', !!this.typeChartInstance, '数据:', this.data.typeChartData?.length);
    if (!this.typeChartInstance) { return; }
    if (!this.data.typeChartData || this.data.typeChartData.length === 0) { return; }
    const option = {
      backgroundColor: 'transparent',
      tooltip: {
        trigger: 'item',
        formatter: (params: any) => {
          if (!params) return '';
          const value = params.value;
          const formatted = value >= 1000 ? (value / 1000).toFixed(1) + 'L' : value + 'ml';
          return `${params.name}: ${formatted} (${params.percent}%)`;
        }
      },
      legend: { bottom: '2%', textStyle: { fontSize: 8, color: '#6b7280' }, itemWidth: 12, itemHeight: 8, itemGap: 8 },
      series: [{
        type: 'pie', radius: ['30%', '70%'], center: ['50%', '45%'],
        data: this.data.typeChartData.map((item: any) => ({ value: item.value, name: item.name, itemStyle: { color: item.color } })),
        label: { show: false }, labelLine: { show: false }, itemStyle: { opacity: 1 }
      }]
    } as any;
    try { this.typeChartInstance.setOption(option); } catch (error) { console.error(LOG_PREFIX + ' 类型图表设置失败:', error); }
  },

  // 跳转到登录页面
  goToLogin() {
    wx.navigateTo({ url: '/pages/login/login' });
  }
});